package com.akkainaction.tool.future;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.Mapper;
import akka.dispatch.OnFailure;
import akka.dispatch.OnSuccess;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.akkainaction.tool.future.actor.FutureActor;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;

/**
 * 异步执行
 */
public class TestAsynFuture {

    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create("sys");
        ActorRef futureActor = system.actorOf(Props.create(FutureActor.class), "futureActor");
        Timeout timeout = new Timeout(Duration.create(3, TimeUnit.SECONDS));
        Future<Object> future = Patterns.ask(futureActor, "hello", timeout);
        try {
            //成功则执行onSuccess
            future.onSuccess(new OnSuccess<Object>() {
                @Override
                public void onSuccess(Object msg) throws Throwable {
                    System.out.println("收到返回消息:[" + msg + "]");
                }
            }, system.dispatcher());
            //失败则执行onFailure
            future.onFailure(new OnFailure() {
                @Override
                public void onFailure(Throwable throwable) throws Throwable {
                    System.out.println("失败原因:" + throwable.getMessage());
                }
            }, system.dispatcher());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
